# -*- encoding:utf-8 -*-
# @Time: 2022/10/19 21:41
# @Author : moran
# @Email: moran@maqu.com
# @File: serializers.py
# @Software: PyCharm

from rest_framework import serializers
from .models import Student, Classes


class StudentSerializer(serializers.ModelSerializer):
    # classes = serializers.StringRelatedField(label='班级')  # 重写 默认展示classes=classes.id,classes=classes.__str__()
    class_name = serializers.CharField(source='classes.name', read_only=True)  # source返回模型对象的字段

    class Meta:
        model = Student
        # fields = '__all__'  # 指定映射的字段 __all__所有的字段
        exclude = ['is_delete']
        extra_kwargs = {
            'age': {'min_value':0, 'max_value':200}
        }

    # def validate_name(self, value):
    #     # 追加额外的逻辑校验，属性级别的，对单个字段进行校验
    #     if 'mq' not in value.lower():
    #         raise serializers.ValidationError('用户名需要包含mq')
    #     return value

    # def validate(self, data):
    #     # 追加额外的逻辑校验-对象级别的，会把传入的所有数据都传入date  date={'name':'moran','age':18}
    #     if 'mq' not in data['name'].lower():
    #         raise serializers.ValidationError('用户名需要包含mq')
    #     elif data['age'] < 18:
    #         raise serializers.ValidationError('未成年禁止访问')
    #     return data

class StudentSerializerSimple(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ['id','name','age','sex']

class ClassesSerializer(serializers.ModelSerializer):
    student_set = StudentSerializerSimple(many=True, read_only=True)  # 嵌套序列化，对管理器进行操作

    class Meta:
        model = Classes
        # fields = '__all__'
        exclude = ['is_delete']